package com.example.bootdemo.utils;


import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.lang.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Random;

public class QRCodeUtil {
    private static final String CHARSET = "utf-8";
    private static final String FORMAT_NAME = "JPG";
    // 二维码尺寸
    private static final int QRCODE_SIZE = 600;
    // LOGO宽度
    private static final int WIDTH = 160;
    // LOGO高度
    private static final int HEIGHT = 160;
    // 图片宽度
    private static final int PH_WIDTH = 600;
    // 图片高度
    private static final int PH_HEIGHT = 800;

    public static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
                hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (imgPath == null || "".equals(imgPath)) {
            return image;
        }
        // 插入图片
        QRCodeUtil.insertImage(image, imgPath, needCompress);
        return image;
    }

    private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
        File file = new File(imgPath);
        if (!file.exists()) {
            System.err.println("" + imgPath + "   该文件不存在！");
            return;
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 压缩LOGO
            if (width > WIDTH) {
                width = WIDTH;
            }
            if (height > HEIGHT) {
                height = HEIGHT;
            }
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    private static void insertQrImage(BufferedImage source, InputStream is, boolean needCompress) throws Exception {
       /* File file = new File(imgPath);
        if (!file.exists()) {
            System.err.println("" + imgPath + "   该文件不存在！");
            return;
        }*/
        Image src = ImageIO.read(is);
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 压缩LOGO
            if (width > WIDTH) {
                width = WIDTH;
            }
            if (height > HEIGHT) {
                height = HEIGHT;
            }
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        // System.out.println(image);
        mkdirs(destPath);
        // String file = new Random().nextInt(99999999)+".jpg";
        // ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
        ImageIO.write(image, FORMAT_NAME, new File(destPath));
    }

    public static BufferedImage encode1(String content, String imgPath, String destPath, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);

        return image;
    }

    public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        return image;
    }

    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        // 当文件夹不存在时，mkdirs会自动创建多层目录，区别于mkdir．(mkdir如果父目录不存在则会抛出异常)
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }





   public static BufferedImage qrcode(String content, InputStream is, boolean needCompress, String note,String remarks) throws Exception {
        BufferedImage image = QRCodeUtil.qrImage(content, is, needCompress, note,remarks);

       /*  String destPath = "D:/qrCode/qrcode/QT126.png";
         mkdirs(destPath);
         ImageIO.write(image, FORMAT_NAME, new File(destPath));*/

        return image;
    } /**/
    public static BufferedImage qrcode2(String content, InputStream is, boolean needCompress, String note,String remarks) throws Exception {
        BufferedImage image = QRCodeUtil.qrImage2(content, is, needCompress, note,remarks);
        return image;
    }
    public static BufferedImage encode(String content, String imgPath, boolean needCompress, String note,String remarks) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress, note,remarks);
        return image;
    }

    private static BufferedImage createImage(String content, String imgPath, boolean needCompress, String note,String remarks) throws Exception {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
                // image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFFFFFFFF : 0xFF000000);
            }
        }
        if (imgPath == null || "".equals(imgPath)) {
            return image;
        }
        // 插入图片
        QRCodeUtil.insertImage(image, imgPath, needCompress);

        BufferedImage outImage = new BufferedImage(PH_WIDTH, PH_HEIGHT, BufferedImage.TYPE_4BYTE_ABGR);

        if (StringUtils.isNotEmpty(note)) {
            // 新的图片，把带logo的二维码下面加上文字
            Graphics2D outg = outImage.createGraphics();
            outg.setColor(Color.WHITE);
            //填充整个屏幕
            outg.fillRect(0,0,PH_WIDTH, PH_HEIGHT);
            // 画二维码到新的面板
            outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            // 画文字到新的面板
            outg.setColor(Color.BLACK);
            int strWidth = note.length();
          //  String remarks ="校园缴费专用";
            int  height1=height + (outImage.getHeight() - height) / 2-5 ;
            int  height2=height + (outImage.getHeight() - height) / 2+85 ;

            if (strWidth > 20) {
                note = note.substring(0, 20);
                outg.setFont(new Font("楷体", Font.BOLD, 28));
                // 画文字
                outg.drawString(note, 0, height1);
                outg.drawString(remarks, 200, height2);

            } else if (18 < strWidth && strWidth <= 20) {
                outg.setFont(new Font("楷体", Font.BOLD, 28));
                outg.drawString(note, 0, height1);
                outg.drawString(remarks, 195, height2);


            } else if (16 < strWidth && strWidth <= 18) {
                outg.setFont(new Font("楷体", Font.BOLD, 30));
                outg.drawString(note, 10, height1);
                outg.drawString(remarks, 190, height2);


            } else if (14 < strWidth && strWidth <= 16) {

                outg.setFont(new Font("楷体", Font.BOLD, 34));
                outg.drawString(note, 10, height1);
                outg.drawString(remarks, 180, height2);


            } else if (12 < strWidth && strWidth <= 14) {
                outg.setFont(new Font("楷体", Font.BOLD, 40));
                outg.drawString(note, 10, height1);
                outg.drawString(remarks, 175, height2);

            } else if (10 < strWidth && strWidth <= 12) {
                outg.setFont(new Font("楷体", Font.BOLD, 46));
                outg.drawString(note, 10, height1);
                outg.drawString(remarks, 163, height2);

            } else if (8 < strWidth && strWidth <= 10) {
                outg.setFont(new Font("楷体", Font.BOLD, 46));
                outg.drawString(note, 60, height1);
                outg.drawString(remarks, 160, height2);

            } else if (6 < strWidth && strWidth <= 8) {
                outg.setFont(new Font("楷体", Font.BOLD, 50));
                outg.drawString(note, 100, height1);
                outg.drawString(remarks, 150, height2);

            } else if (4 < strWidth && strWidth <= 6) {
                outg.setFont(new Font("楷体", Font.BOLD, 50));
                outg.drawString(note, 150, height1);
                outg.drawString(remarks, 147, height2);

            }  else if (2 < strWidth && strWidth <= 4) {
                outg.setFont(new Font("楷体", Font.BOLD, 50));
                outg.drawString(note, 200, height1);
                outg.drawString(remarks, 146, height2);

            } else {
                outg.setFont(new Font("楷体", Font.BOLD, 50));
                outg.drawString(note, 250, height1);
                outg.drawString(remarks, 145, height2);

            }

            //outg.setFont(new Font("楷体", Font.BOLD, 30)); // 字体、字型、字号

            //  outg.drawString(note, 300 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12); // 画文字
            outg.dispose();
            outImage.flush();
            image = outImage;
        }


        return image;
    }
    private static BufferedImage qrImage(String content, InputStream is, boolean needCompress, String note,String remarks) throws Exception {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
                // image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFFFFFFFF : 0xFF000000);
            }
        }
       /* if (imgPath == null || "".equals(imgPath)) {
            return image;
        }*/
        // 插入图片
        if (is!=null){
            QRCodeUtil.insertQrImage(image, is, needCompress);
        }


        BufferedImage outImage = new BufferedImage(PH_WIDTH, PH_HEIGHT, BufferedImage.TYPE_4BYTE_ABGR);

        if (StringUtils.isNotEmpty(note)) {
            // 新的图片，把带logo的二维码下面加上文字
            Graphics2D outg = outImage.createGraphics();

            outg.setColor(Color.WHITE);
            //填充整个屏幕
            outg.fillRect(0,0,PH_WIDTH, PH_HEIGHT);
            // 画二维码到新的面板
            outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            // 画文字到新的面板
            outg.setColor(Color.BLACK);
            int strWidth = note.length();
          //  String remarks ="校园缴费专用";
            int  height1=height + (outImage.getHeight() - height) / 2-5 ;
            int  height2=height + (outImage.getHeight() - height) / 2+85 ;

            if (strWidth > 20) {
                note = note.substring(0, 20);
                outg.setFont(new Font("楷体", Font.BOLD, 28));
                // 画文字
                outg.drawString(note, 0, height1);
               // outg.drawString(remarks, 200, height2);

            } else if (18 < strWidth && strWidth <= 20) {
                outg.setFont(new Font("楷体", Font.BOLD, 28));
                outg.drawString(note, 0, height1);
               // outg.drawString(remarks, 195, height2);


            } else if (16 < strWidth && strWidth <= 18) {
                outg.setFont(new Font("楷体", Font.BOLD, 30));
                outg.drawString(note, 10, height1);
              //  outg.drawString(remarks, 190, height2);


            } else if (14 < strWidth && strWidth <= 16) {

                outg.setFont(new Font("楷体", Font.BOLD, 34));
                outg.drawString(note, 10, height1);
              //  outg.drawString(remarks, 180, height2);


            } else if (12 < strWidth && strWidth <= 14) {
                outg.setFont(new Font("楷体", Font.BOLD, 40));
                outg.drawString(note, 10, height1);
              //  outg.drawString(remarks, 175, height2);

            } else if (10 < strWidth && strWidth <= 12) {
                outg.setFont(new Font("楷体", Font.BOLD, 46));
                outg.drawString(note, 10, height1);
             //   outg.drawString(remarks, 163, height2);

            } else if (8 < strWidth && strWidth <= 10) {
                outg.setFont(new Font("楷体", Font.BOLD, 46));
                outg.drawString(note, 60, height1);
             //   outg.drawString(remarks, 160, height2);

            } else if (6 < strWidth && strWidth <= 8) {
                outg.setFont(new Font("楷体", Font.BOLD, 50));
                outg.drawString(note, 100, height1);
             //   outg.drawString(remarks, 150, height2);

            } else if (4 < strWidth && strWidth <= 6) {
                outg.setFont(new Font("楷体", Font.BOLD, 50));
                outg.drawString(note, 150, height1);
             //   outg.drawString(remarks, 147, height2);

            }  else if (2 < strWidth && strWidth <= 4) {
                outg.setFont(new Font("楷体", Font.BOLD, 50));
                outg.drawString(note, 200, height1);
            //    outg.drawString(remarks, 146, height2);

            } else {
                outg.setFont(new Font("楷体", Font.BOLD, 50));
                outg.drawString(note, 250, height1);
             //   outg.drawString(remarks, 145, height2);

            }
            outg.setFont(new Font("楷体", Font.BOLD, 50));
            outg.drawString(remarks, 6, height2);
            //outg.setFont(new Font("楷体", Font.BOLD, 30)); // 字体、字型、字号

            //  outg.drawString(note, 300 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12); // 画文字
            outg.dispose();
            outImage.flush();
            image = outImage;
        }


        return image;
    }
    private static BufferedImage qrImage2(String content, InputStream imgPath, boolean needCompress, String note,String remarks) throws Exception {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
                // image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFFFFFFFF : 0xFF000000);
            }
        }
       /* if (imgPath == null || "".equals(imgPath)) {
            return image;
        }*/
        // 插入图片
       // QRCodeUtil.insertQrImage(image, imgPath, needCompress);

        BufferedImage outImage = new BufferedImage(PH_WIDTH, PH_HEIGHT, BufferedImage.TYPE_4BYTE_ABGR);

        if (StringUtils.isNotEmpty(note)) {
            // 新的图片，把带logo的二维码下面加上文字
            Graphics2D outg = outImage.createGraphics();
            outg.setColor(Color.WHITE);
            //填充整个屏幕
            outg.fillRect(0,0,PH_WIDTH, PH_HEIGHT);
            // 画二维码到新的面板
            outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            // 画文字到新的面板
            outg.setColor(Color.BLACK);
            int strWidth = note.length();
            //  String remarks ="校园缴费专用";
            int  height1=height + (outImage.getHeight() - height) / 2-5 ;
            int  height2=height + (outImage.getHeight() - height) / 2+85 ;

            if (strWidth > 20) {
                note = note.substring(0, 20);
                outg.setFont(new Font("楷体", Font.BOLD, 28));
                // 画文字
                outg.drawString(note, 0, height1);
                outg.drawString(remarks, 200, height2);

            } else if (18 < strWidth && strWidth <= 20) {
                outg.setFont(new Font("楷体", Font.BOLD, 28));
                outg.drawString(note, 0, height1);
                outg.drawString(remarks, 195, height2);


            } else if (16 < strWidth && strWidth <= 18) {
                outg.setFont(new Font("楷体", Font.BOLD, 30));
                outg.drawString(note, 10, height1);
                outg.drawString(remarks, 190, height2);


            } else if (14 < strWidth && strWidth <= 16) {

                outg.setFont(new Font("楷体", Font.BOLD, 34));
                outg.drawString(note, 10, height1);
                outg.drawString(remarks, 180, height2);


            } else if (12 < strWidth && strWidth <= 14) {
                outg.setFont(new Font("楷体", Font.BOLD, 40));
                outg.drawString(note, 10, height1);
                outg.drawString(remarks, 175, height2);

            } else if (10 < strWidth && strWidth <= 12) {
                outg.setFont(new Font("楷体", Font.BOLD, 46));
                outg.drawString(note, 10, height1);
                outg.drawString(remarks, 163, height2);

            } else if (8 < strWidth && strWidth <= 10) {
                outg.setFont(new Font("楷体", Font.BOLD, 46));
                outg.drawString(note, 60, height1);
                outg.drawString(remarks, 160, height2);

            } else if (6 < strWidth && strWidth <= 8) {
                outg.setFont(new Font("楷体", Font.BOLD, 50));
                outg.drawString(note, 100, height1);
                outg.drawString(remarks, 150, height2);

            } else if (4 < strWidth && strWidth <= 6) {
                outg.setFont(new Font("楷体", Font.BOLD, 50));
                outg.drawString(note, 150, height1);
                outg.drawString(remarks, 147, height2);

            }  else if (2 < strWidth && strWidth <= 4) {
                outg.setFont(new Font("楷体", Font.BOLD, 50));
                outg.drawString(note, 200, height1);
                outg.drawString(remarks, 146, height2);

            } else {
                outg.setFont(new Font("楷体", Font.BOLD, 50));
                outg.drawString(note, 250, height1);
                outg.drawString(remarks, 145, height2);

            }

            //outg.setFont(new Font("楷体", Font.BOLD, 30)); // 字体、字型、字号

            //  outg.drawString(note, 300 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12); // 画文字
            outg.dispose();
            outImage.flush();
            image = outImage;
        }


        return image;
    }
    public static void encode(String content, String imgPath, String destPath, boolean needCompress, String note,String remarks) throws Exception {
      //  BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress, note,remarks);
        InputStream is=null;
       // BufferedImage image = QRCodeUtil.qrcode2(content, is, needCompress, note,remarks);
      //  BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress, note,remarks);
        BufferedImage image = QRCodeUtil.qrImage2(content, is, needCompress, note,remarks);

        // System.out.println(image);
       //  mkdirs(destPath);
         //String file = new Random().nextInt(99999999)+".jpg";
        //  ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
        ImageIO.write(image, FORMAT_NAME, new File(destPath));
    }
    public static void main(String[] args) throws Exception {
        String text="URL";
        String orgName="中文测试1";
        String remarks="中文测试2";
        String destPath=new Random().nextInt(99999999)+"user.png";
      //String dirurl=  System.getProperty("user.dir");
      //  System.out.println(dirurl);
        QRCodeUtil.encode(text, null,destPath, true, orgName, remarks);
    }
}
